"""
公共方法
"""
import logging
import string
import random
import traceback
import os

from werkzeug.utils import secure_filename

from common.models import db
from common.models.video import Video
from define.define import IP_PORT, BASE_URL

from common.models.user import UserBase
from common.utils.captcha import Captcha

# 容联
accId = '8aaf07087f77bf96017fd54021082f71'
accToken = 'fcc9d94e2c324d32a93081fe8323c959'
appId = '8aaf07087f77bf96017fd54021ff2f78'

# 七牛
# 需要填写你的 Access Key 和 Secret Key
access_key = 'ZxuCr1dxnenWx0-gGIBZcxOMcjytXtZISwgix36L'
secret_key = 'SJl9JmW7zB0j1xHlDPmyjTwJf5E7ksoQicqIDQT8'


def generate_code():
    return Captcha.gene_graph_captcha()


def random_string_generator(str_size):
    allowed_chars = string.ascii_uppercase + string.digits
    return ''.join(random.choice(allowed_chars) for x in range(str_size))


def upload():
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'wangyufei911'
    # 上传后保存的文件名
    key = 'test/aaa.py'
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # 要上传文件的本地路径
    localfile = './main.py'
    ret, info = put_file(token, key, localfile)
    print(info)
    print(ret)
    assert ret['key'] == key
    assert ret['hash'] == etag(localfile)


def download():
    """

    """
    q = Auth(access_key, secret_key)
    base_url = 'http://%s/%s' % ('wangyufei911', 'test/aaa.py')
    private_url = q.private_download_url(base_url, expires=3600)
    print(private_url)
    r = requests.get(private_url)
    assert r.status_code == 200


def get_upload_token():
    """
    获取上传文件的token
    :return:
    """
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'courses1'
    # 上传后保存的文件名
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, 3600)
    return token


def check_is_manager(user_id):
    """
    检查用户是否为管理员
    :return:
    """
    user = UserBase.query.get(user_id)
    # 判断该用户有没有添加的权限
    if user.is_superuser == 0:
        return False
    return True


def upload_file(appkey_id, request, UPLOAD_PATH):
    """
    上传文件
    :param appkey_id:
    :param request:
    :param UPLOAD_PATH:
    :return:
    """
    try:
        user = UserBase.get_user_by_appkey_id(appkey_id)
        if not user:
            return {'message': 'appkey_id is error'}, 408

        # 创建文件夹路径
        upload_path = os.path.join(UPLOAD_PATH, appkey_id)
        if os.path.exists(upload_path):
            pass
        else:
            os.mkdir(upload_path)

        f = request.files['file']
        # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
        upload_path = os.path.join(upload_path, secure_filename(f.filename))
        f.save(upload_path)
        url = 'http://{}:{}/file/video/{}?appkey_id={}'.format(BASE_URL, IP_PORT, f.filename, user.appkey_id)

        # 如果已有当前同名文件数据，进行覆盖操作
        video = Video.query.filter_by(upload_path=url).first()
        if video:
            video.upload_path = url
        else:
            video = Video(user=user.id, upload_path=url)
            db.session.add(video)
        db.session.commit()
        return {'message': 'ok', 'code': 200, 'data': {'upload_path': url}}
    except:
        error = traceback.format_exc()
        logging.error('UploadVideo error:{}'.format(error))
        return {'message': error, 'code': 500}
